//
//  WalletController.m
//  FbeeAPP
//
//  Created by dev-m on 2018/3/7.
//  Copyright © 2018年 mohao. All rights reserved.
//

#import "WalletController.h"
#import "EmptyViewHelper.h"
#import "FbeeCommitBtn.h"
#import "MyWalletHeader.h"
#import "MyWalletCell.h"

#import "RegexKitLite.h"
#import "UIScrollView+BCYRefresh.h"
#import "CacheHelper.h"
#import "WalletObj.h"

#define TimeSpace  5*60

@interface WalletController ()<UITableViewDelegate,UITableViewDataSource>
{
    UITableView *walletView;
    NSString *refrshTime;
    MyWalletHeader *header;
    NSMutableArray *listArray;
    NSMutableArray *dataArray;
    
    UIView *addWalletView;
    FbeeCommitBtn *addBtn;
    
}

@end

@implementation WalletController

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.largeTitle setTitle:NSLocalizedString(@"tNavUCenterWallet", nil)];
    listArray = [[NSMutableArray alloc] init];
    dataArray = [[NSMutableArray alloc] init];
    
    //添加钱包成功
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(buildView) name:Notification_AddWalletClose object:nil];
    
    [self buildView];
}

-(void)buildView
{
    [addWalletView removeFromSuperview];
    [walletView removeFromSuperview];
    
    //无钱包
    if (![UserInfoManager sharedManager].haveWallet) {
        
        [self addWalletView];
    }
    //有钱包
    else
    {
        [self myWalletView];
    }
}

-(void)addWalletView
{
    if (!addWalletView) {
        
        addWalletView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, IPHONEWIDTH, IPHONEHEIGHT)];
        
        UILabel *infoL  = [UILabel makeLabel:^(TTLabelExtend *make) {
            make.addText(NSLocalizedString(@"textAddWallet", nil));
            make.addFont([UIFont systemFontOfSize:16.0f]).addTextColor(FBEE_COLOR_TEXT);
            make.textAlignment = NSTextAlignmentCenter;
            make.setFrame(CGRectMake(0, self.largeTitle.bottom + 105, IPHONEWIDTH, 18));
            [addWalletView addSubview:make];
        }];
        
        
        addBtn = [[FbeeCommitBtn alloc] initWithTitle:NSLocalizedString(@"uCenterAddWallet", nil)];
        addBtn.centerX = IPHONEWIDTH/2;
        addBtn.top = infoL.bottom + 110;
        [addBtn onClick:^{
            [[JumpManager sharedManager] jumpToMyWalletAdd];
        }];
        
        [addWalletView addSubview:addBtn];
    }
    
    [self.view insertSubview:addWalletView atIndex:0];

}

-(void)myWalletView
{
    if(!walletView)
    {
        header = [[MyWalletHeader alloc] initWithFrame:CGRectMake(0, 0, IPHONEWIDTH, 130*UISCALE)];
        @weakify(self)
        header.onDel = ^{
            @strongify(self)
            [self deleteWallet];
        };
        
        walletView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.largeTitle.bottom, IPHONEWIDTH, IPHONEHEIGHT - self.largeTitle.bottom) style:UITableViewStylePlain];
        walletView.separatorStyle = UITableViewCellSeparatorStyleNone;
        walletView.alwaysBounceVertical = YES;
        walletView.backgroundColor = [UIColor clearColor];
        walletView.delegate = self;
        walletView.dataSource = self;
        walletView.tableHeaderView = header;
        
        
        [walletView addHeaderByRefreshHandler:^{
            @strongify(self)
            [self getEthAllToken];
        }];
    }
    
    [self.view addSubview:walletView];
    
    [self getEthAllToken];
}

#pragma mark - TableView Cell

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view  = [[UIView alloc] initWithFrame:CGRectMake(0, 0, IPHONEWIDTH, 30)];
    view.backgroundColor = COLOR_WHITE;
    NSDictionary *dict = [CacheHelper getDictionaryByFilePath:WalletDataCachePath];
    
    NSTimeInterval lastime = SafeGetDoubleValue([dict objectForKey:@"refreshTime"]);
    NSDate *oDate = [NSDate dateWithTimeIntervalSince1970:lastime];
    NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
    NSTimeZone* destinationTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
    NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:oDate];
    NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:oDate];
    NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
    NSDate* currentDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:oDate];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];// 创建一个时间格式化对象
    [dateFormatter setDateFormat:@"yyyy.MM.dd hh:mm"];//设定时间格式,这里可以设置成自己需要的格式
    refrshTime = [NSString stringWithFormat:@"数据更新于 %@",[dateFormatter stringFromDate:currentDate]];//将时间转化成字符串
    
    UILabel *info = [UILabel makeLabel:^(TTLabelExtend *make) {
        make.addTextColor(FBEE_COLOR_INFO).addFont([UIFont systemFontOfSize:14.0f]);
        make.addText(refrshTime);
        make.setFrame(CGRectMake(16, 0, IPHONEWIDTH - 16, view.height));
        [view addSubview:make];
    }];
    
    UIButton *btn = [UIButton makeButton:^(TTButtonExtend *make) {
        make.addTitleColor(FBEE_COLOR_BLUE,UIControlStateNormal).addFont([UIFont systemFontOfSize:14]);
        make.addTitle(@"点击刷新");
        make.addTarget(self,@selector(onRefresh));
        make.setFrame(CGRectMake(0, 0, 60, 30));
        make.right = IPHONEWIDTH-21;
        [view addSubview:make];
    }];
    
    return view;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return listArray.count;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 70;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellId = @"CELLID";
    
    WalletObj *obj = [listArray objectAtIndex:indexPath.row];
    
    MyWalletCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    
    if (!cell) {
        cell = [[MyWalletCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    }
    
    [cell CellByObj:obj];
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

}

-(void)reLoadMainTable
{
}


#pragma mark - request

-(void)deleteWallet
{
    [self post:WalletRemove_URL param:@{@"uid":[UserInfoManager sharedManager].userId,@"address":[UserInfoManager sharedManager].walletAddr} code:WalletRemove_URL_Code];
}


#pragma mark - 首选方案

-(void)getEthAllToken
{

    
    //加载web数据
    if ([self checkCanLoadData]) {
        
        if ([LoadingHelper isLoadingFromView:self.view]) {
            [walletView endRefreshing];
            return;
        }
        
        if (![walletView isLoading]) {
            [LoadingHelper showLoadingOnView:self.view];
        }

        [listArray removeAllObjects];
        NSString *url = [NSString stringWithFormat:@"%@/%@?apiKey=hwkr9922SruFpI74",EtherAllTokenAPI_URL,[UserInfoManager sharedManager].walletAddr];
        [self getDataByUrl:url code:EtherAllTokenAPI_URL_Code];
    }
    //缓存中加载
    else
    {
        [walletView endRefreshing];
        [LoadingHelper removeLoadingOnView:self.view];
        [listArray removeAllObjects];
        for (NSDictionary *dict in SafeGetArrayValue([[CacheHelper getDictionaryByFilePath:WalletDataCachePath] objectForKey:@"data"])) {
            WalletObj *obj = [[WalletObj alloc] init];
            [obj setDataByDict:dict];
            [listArray addObject:obj];
        };
        
    }
    

}

#pragma mark - 备选方案

-(void)getWalletInfo{
    
    [dataArray removeAllObjects];
    [self getEthBalance];
}

//获取区块浏览器
-(void)getEthInfo
{
    NSString *url = [NSString stringWithFormat:@"%@/%@",Etherscan_URL,[UserInfoManager sharedManager].walletAddr];
    [self getDataByUrl:url code:Etherscan_URL_Code];
}

//区块ETH 余额
-(void)getEthBalance
{
    NSString *url = [NSString stringWithFormat:@"%@&address=%@&tag=latest&apikey=TKWWQ1B85EUM22HK81ECE4ZJA7DZ5VHNDX",EtherAPI_URL,[UserInfoManager sharedManager].walletAddr];
    [self getDataByUrl:url code:EtherAPI_URL_Code];
}

#pragma mark - response

-(void)requestSuccess:(id)data code:(NSInteger)code
{
    if (code == WalletRemove_URL_Code) {
        
        [UserInfoManager sharedManager].walletAddr = @"";
        [header removeAllSubviews];
        header = nil;
        [walletView removeFromSuperview];
        walletView = nil;
        
        [self buildView];
    }
}

-(void)requestLogicError:(id)data code:(NSInteger)code
{
    [super requestLogicError:data code:code];
}

-(void)requestFailure:(NSError *)error code:(NSInteger)code
{
    //首选方案请求失败
    if (code == EtherAllTokenAPI_URL_Code) {
        [self getWalletInfo];
        NSLog(@"首选方案请求失败");
    }
    
    //备选方案请求失败
    if (code == Etherscan_URL_Code || code == EtherAPI_URL_Code) {
        [walletView endRefreshing];
        [LoadingHelper removeLoadingOnView:self.view];
        NSLog(@"备选方案请求失败");
    }
}

-(void)requestData:(NSData *)data code:(NSInteger)code
{
    //首选方案成功
    if (code == EtherAllTokenAPI_URL_Code) {
        NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        
        //判断是否ERROR  ERROR走备选请求
        if (!dataDict) {
            [self getWalletInfo];
            return;
        }
        
        WalletObj *obj = [[WalletObj alloc] init];
        obj.name = @"ETH";
        obj.symbol = @"ETH";
        obj.balance = SafeGetStringValue([SafeGetDictionaryValue([dataDict objectForKey:@"ETH"]) objectForKey:@"balance"]);
        [listArray addObject:obj];
        
        for (NSDictionary *dict in SafeGetArrayValue([dataDict objectForKey:@"tokens"])) {
            WalletObj *obj = [[WalletObj alloc] init];
            //数据转1维
            NSMutableDictionary *md = [[NSMutableDictionary alloc] initWithDictionary:SafeGetDictionaryValue([dict objectForKey:@"tokenInfo"])];
            [md setObject:SafeGetStringValue([dict objectForKey:@"balance"]) forKey:@"balance"];
            [obj setDataByDict:md];
            [listArray addObject:obj];
        }
        
        NSDate *oDate = [NSDate date];
        [walletView reloadData];
        [walletView endRefreshing];
        [LoadingHelper removeLoadingOnView:self.view];
        
        //缓存数据
        NSMutableArray *tmp = [[NSMutableArray alloc] init];
        for (WalletObj *obj in listArray) {
            [tmp addObject:[obj getDictbyData]];
        }
        
        NSDictionary *cache = @{@"addr":[UserInfoManager sharedManager].walletAddr,@"refreshTime":@([oDate timeIntervalSince1970]),@"data":tmp};
        [CacheHelper saveCacheDictionary:cache path:WalletDataCachePath];
        
        NSLog(@"首选方案请求成功 %@",listArray);
        
    }
    
    
    //备选方案
    {
        //区块链 API 调用成功
        if (code == EtherAPI_URL_Code) {
            NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            
            if ([SafeGetStringValue([dataDict objectForKey:@"status"]) isEqualToString:@"1"]) {
                NSDecimalNumber *bnum = [[NSDecimalNumber alloc] initWithString:SafeGetStringValue([dataDict objectForKey:@"result"])];
                NSDecimalNumber *dd = [[NSDecimalNumber alloc] initWithString:@"1000000000000000000"];
                
                NSString *ethB = [NSString stringWithFormat:@"%@",[bnum decimalNumberByDividingBy:dd]];
                
                WalletObj *obj = [[WalletObj alloc] init];
                obj.name = @"ETH";
                obj.symbol = @"ETH";
                obj.balance = ethB;
                [dataArray addObject:obj];
                
                [self getEthInfo];
            }
            else
            {
                [walletView endRefreshing];
                [LoadingHelper removeLoadingOnView:self.view];
                [NoticePopHelper showNoticeText:SafeGetStringValue([dataDict objectForKey:@"result"])];
            }
            
        }
        
        //区块浏览器请求成功
        if (code == Etherscan_URL_Code) {
            
            NSString *dataStr = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] lowercaseString];
            dataStr = [dataStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
            
            //        //查找余额
            //        NSString *ethB = [dataStr stringByMatching:@"<td>eth balance:</td><td>(.*?)</td>"];
            //        //保留数据部分
            //        ethB = [ethB stringByReplacingOccurrencesOfRegex:@"<td>eth balance:</td>" withString:@""];
            //        ethB = [ethB stringByReplacingOccurrencesOfRegex:@"[^/s*]ether" withString:@""];
            //        //替换标签
            //        ethB = [ethB stringByReplacingOccurrencesOfRegex:@"<[^>]*>" withString:@""];
            
            NSArray *rArray = [dataStr componentsMatchedByRegex:@"<a href='/token/([^\\?]*)[\\s\\S]*?</b><br>([0-9,.]*).([^<]*)"];
            
            
            for (NSString *str in rArray) {
                NSString *bstr = [str stringByMatching:@"<br>.+"];
                //保留数据部分
                bstr = [bstr stringByReplacingOccurrencesOfRegex:@"<br>" withString:@""];
                NSArray *bary = [bstr componentsSeparatedByString:@" "];
                if (bary.count == 2) {
                    WalletObj *obj = [[WalletObj alloc] init];
                    obj.name = [[bary objectAtIndex:1] uppercaseString];
                    obj.symbol = [[bary objectAtIndex:1] uppercaseString];
                    obj.balance = [bary objectAtIndex:0];
                    [dataArray addObject:obj];
                }
            }
            
            [listArray removeAllObjects];
            [listArray addObjectsFromArray:dataArray];
            
            NSDate *oDate = [NSDate date];
            [walletView reloadData];
            [walletView endRefreshing];
            [LoadingHelper removeLoadingOnView:self.view];
            
            //缓存数据
            NSMutableArray *tmp = [[NSMutableArray alloc] init];
            for (WalletObj *obj in listArray) {
                [tmp addObject:[obj getDictbyData]];
            }
            
            NSDictionary *cache = @{@"addr":[UserInfoManager sharedManager].walletAddr,@"refreshTime":@([oDate timeIntervalSince1970]),@"data":tmp};
            [CacheHelper saveCacheDictionary:cache path:WalletDataCachePath];
            
            NSLog(@"备选方案请求成功 %@",listArray);
        }
    }
    
    
    
}

-(void)onRefresh
{
    if (![self checkCanLoadData])
    {
        [NoticePopHelper showNoticeText:NSLocalizedString(@"textWalletGetData", nil)];
    }
    [self getEthAllToken];
}

-(BOOL)checkCanLoadData
{
    //检查本地是否有缓存
    NSDictionary *dict = [CacheHelper getDictionaryByFilePath:WalletDataCachePath];
    
    if (!dict) {
        return YES;
    }
    NSString *addr = SafeGetStringValue([dict objectForKey:@"addr"]);
    if (![addr isEqualToString:[UserInfoManager sharedManager].walletAddr]) {
        return YES;
    }
    
    NSTimeInterval lastTime = SafeGetDoubleValue([dict objectForKey:@"refreshTime"]);
    NSTimeInterval nowTime = [[NSDate date] timeIntervalSince1970];
    if (nowTime - lastTime > TimeSpace) {
        return YES;
    }
    
    return NO;
}


@end
